/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.prototype.vaadin;

/**
 *
 * @author zineddine
 */
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;


public final class PremiereConnection {

    private  String urlPrincipale=null;                  
    private  Document sf_page =null; //contient le code HTML d'une page
             ConcurrentHashMap<String,String> concurrentMap;
    private  ArrayList<String> listUrlPage;
         
    public PremiereConnection(String urlPrincipale) {
        try {
            this.urlPrincipale=urlPrincipale;
            
            concurrentMap = new ConcurrentHashMap<String,String>();
           
            parsePage(urlPrincipale);
            
        } catch (IOException ex) {
            Logger.getLogger(PremiereConnection.class.getName()).log(Level.SEVERE, null, ex);
        } 
        
    } 

	
    
        /* cette méthode retourne le nombre 
         * de pages web, contenant les projets
         */
    
	public int nbPage(){
            String oneofnbpage = sf_page.getElementById("result_count").text();
            int last = oneofnbpage.lastIndexOf(".");
            int lastvide = oneofnbpage.lastIndexOf(" ");
            lastvide++;
            String s = oneofnbpage.substring(lastvide, last);
            int nbPage=Integer.parseInt(s);
            return nbPage;
	}
	public void parsePage(String urlPage) throws IOException{
                sf_page = Jsoup.connect(urlPage).timeout(0).get();
		Element resultat = sf_page.getElementById("result_data");
                Elements links = resultat.getElementsByTag("a");
               
                for (Element link : links) {
                       
                    String linkHref = link.attr("href");
                    String linkText = link.text();
                    concurrentMap.put(linkText, linkHref);

               } 
               listUrlPage =urlPage();
	}
        
	
        /*
         * comme la recherche fournit 
         * plusieurs projets sur différentes 
         * page on est obligé de traiter page
         * par page, cela ce fait on ayant une
         * pour chaque page
         */
	public ArrayList<String> urlPage(){
		final String autrepage = "?page=";
		ArrayList<String> URLs_de_Pages= new ArrayList<String>();
		int nbpage= nbPage();   //on aura le nombre totale de pages
                if(nbpage!=1){
                    for(int i=2;i<=nbpage;i++){
                            String s = Integer.toString(i); 
                            URLs_de_Pages.add(getUrlPrincipale()+autrepage+s);
                    }
                }
		return URLs_de_Pages;
		
	}
        
	
	

    /**
     * @return the urlPrincipale
     */
    public String getUrlPrincipale() {
        return urlPrincipale;
    }

    /**
     * @return the malist_de_lien
     */
    
    public Document getSf_page() {
        return sf_page;
    }
    /*
    public static void main(String[] args) throws IOException, InterruptedException, InterruptedException, InterruptedException, InterruptedException, ExecutionException {
	
       
        
       PremiereConnection test;
       test = new PremiereConnection("http://sourceforge.net/directory/os:windows/os:bsd/freshness:recently-updated/"); 
       
       int numWorkers = test.nbPage();
       numWorkers--;    
       
        ExecutorService pooldynamique = Executors.newCachedThreadPool();
        
            
        JobThread workers[] = new JobThread[numWorkers];
        Future<ConcurrentHashMap<String,String>> futures[] = new Future[numWorkers];
        
        for(int i=0;i<numWorkers;i++){
			//Thread.sleep(2000);
			
                        workers[i] = new JobThread(test.urlPage().get(i));
                        futures[i]= pooldynamique.submit(workers[i]);
        }
             
        pooldynamique.shutdown();
           
        for (int i = 0; i < numWorkers; i++) {
            try {
                    
                    test.concurrentMap.putAll((futures[i].get()));
            } catch (Exception e) {}
        }
       
                    
                
                        
        for(ConcurrentHashMap.Entry<String,String> entry : test.concurrentMap.entrySet()) {
           
                    String cle = entry.getKey();
                    String valeur = entry.getValue();
                    System.out.println("Nom: "+cle +" Lien: "+valeur);
       }
       
    }
    * /
    * /*/
}
